package bo.zhao.event.custom.publisher;

import bo.zhao.event.custom.event.CustomEvent;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

/**
 * @author ZhaoBo (zhaobo@shanshu.ai)
 * @date 2022/4/2
 */
@Component
public class CustomEventPublisher implements ApplicationContextAware {

    /**
     * 使用ApplicationEventPublisher发布事件
     *
     * @Autowired private ApplicationEventPublisher eventPublisher;
     * <p>
     * <p>
     * 直接使用ApplicationContext发布事件
     * 当然获取ApplicationContext方式，除了直接注入外，也可以通过实现Aware接口的方式，来注入ApplicationContext上下文对象
     */
    private ApplicationContext applicationContext;

    /**
     * 事件发布除了用ApplicationEventPublisher发布器外还有很多，当然我们也直接可以用ApplicationContext上下文容器来发布事件
     *
     * @param message
     */
    public void publish(String message) {
        CustomEvent event = new CustomEvent(this, message);
        //eventPublisher.publishEvent(event);
        applicationContext.publishEvent(event);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
